#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:   analysis_restful_testcase.py.py
   Remark :     解析 restful 接口测试用例
-------------------------------------------------
"""

import os
import re
import json

from urllib.parse import parse_qsl
from apitesting.config import DATA_DIR as DATA_PATH
from apitesting.common.file.yaml_handler import ReadYaml
from apitesting.src.models.test_suite.test_suite_model import TestSuite
from apitesting.src.base.get_env import get_env
from apitesting.src.base.custom_parameters import call_back


class AnalysisRestfulTestCase:
    def __init__(self, file_url):
        self.file_url = os.path.join(DATA_PATH, file_url)
        self.file_data = ReadYaml(self.file_url).get_data()

    def analysis_testcase(self) -> list[TestSuite]:
        # 创建用例合集
        testcases: list[TestSuite] = []
        # 读取环境,获取指定环境的用例
        env = get_env()

        url = self.file_data["url"][env]
        method = self.file_data["method"].lower()

        for case in self.file_data["case_datas"]:
            if env == str(case["env"]).lower():
                testcase = TestSuite()
                testcase.url = url
                testcase.method = method
                testcase.case_title = case["case_title"]
                # if len(case["check"]) != len(case["result"]):
                #     raise LenError(f"用例:--{testcase.case_title}--校验点和校验规则的数量不一致")

                # testcase.check = case["check"]
                # testcase.result = case["result"]
                testcase.assertions = case["Assertions"]

                case_data = str(case["case_data"])
                case_data = re.sub("#(.*?)#", call_back, case_data)
                if testcase.method == "get" and ("&" in case_data or "=" in case_data):
                    testcase.case_data = dict(parse_qsl(case_data))
                else:
                    testcase.case_data = json.loads(case_data)
                testcases.append(testcase)
        return testcases
